package com.shiroa.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shiroa.common.Token;
import com.shiroa.entity.SysMenu;
import com.shiroa.entity.SysRole;
import com.shiroa.entity.SysUser;
import com.shiroa.entity.vo.LoginUser;
import com.shiroa.entity.vo.LoginVo;
import com.shiroa.mapper.SysUserMapper;
import com.shiroa.redis.RedisUtil;
import com.shiroa.service.ISysMenuService;
import com.shiroa.service.ISysRoleService;
import com.shiroa.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.security.auth.login.LoginException;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class LoginServiceImp extends ServiceImpl<SysUserMapper, SysUser> implements LoginService {
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysMenuService iSysMenuService;
    @Autowired
    RedisUtil redisUtil;
    @Override
    public Token login(LoginVo loginVo) throws RuntimeException, JsonProcessingException {
        SysUser user = getBaseMapper().selectOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserName, loginVo.getUsername()));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!user.getPassword().equals(loginVo.getPassword())) {
            throw new RuntimeException("密码不存在");
        }
        List<SysRole> list =sysRoleService.getByUserId(user.getUserId());
        if(list.isEmpty()){
            throw new RuntimeException("请先授权");
        }
        List<Long> roleIdList = list.stream().mapToLong(SysRole::getRoleId).boxed().collect(Collectors.toList());
        List<SysMenu> menuList = iSysMenuService.getByRoleIdList(roleIdList);
        Set<String> roleNames = list.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        Set<String> permeList = menuList.stream().filter(item -> StringUtils.hasText(item.getPerms()))
                .map(SysMenu::getPerms).collect(Collectors.toSet());
        String uuid = UUID.randomUUID().toString();
        LoginUser loginUser = new LoginUser();
        loginUser.setNickName(user.getNickName());
        loginUser.setUsername(user.getUserName());
        loginUser.setPermsList(permeList);
        loginUser.setRoleKeyList(roleNames);
        redisUtil.set(uuid,new ObjectMapper().writeValueAsString(loginUser),1800);
        Token token = new Token();
        token.setToken(uuid);
        return token;
    }

    @Override
    public void logout(String token) {
       if(token!=null){
           redisUtil.del(token);
       }else {
         throw new RuntimeException("退出登录失败");
       }

    }
}
